<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery 实现的待办事项</title>
</head>
<body>
<input id="textInput" type="text" placeholder="Task to be done...">
<button id="addBtn">Add</button>
<div id="tasks"></div>

<script src="jquery-3.7.1.min.js"></script>
<script>
    $(function () {
        $("#addBtn").bind('click', function () {
            addTask();
        })

        $("#textInput").bind('keypress', function (event) {
            if (event.key === "Enter") {
                addTask();
            }
        })
    });

    function addTask() {
        let textInput = $("#textInput");
        let textInputValue = textInput.val(); // 元素 js 访问的是 value 属性，jQuery 是访问 val() 方法
        let taskContent = textInputValue.trim();
        if (taskContent.length === 0) {
            alert("请输入内容");
        } else {
            $("#tasks").append(`<div class='task'>
                    <input class="task-checkbox" type="checkbox" />
                    <span class="task-content">${taskContent}</span>
                    <button class="delete"><i>x</i></button>
                </div>`);

            textInput.val('');


            $(".task-checkbox").each(function () {
                $(this).bind('click', function () {
                    this.nextElementSibling.setAttribute("style", `text-decoration: ${this.checked ? 'line-through' : 'none'};`);
                })
            });

            $(".delete").each(function () {
                $(this).bind('click', function () {
                    this.parentNode.remove();
                })
            });
        }
    }
</script>
</body>
</html>